import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide SnackPosition;
import 'package:image_picker/image_picker.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import '../../common/index.dart';
import '../index.dart';
import 'widgets/index.dart';

class SettingController extends GetxController {
  SettingController();

  // 表单控制器
  final TextEditingController name_controller = TextEditingController();
  final TextEditingController old_password_controller =
      TextEditingController();
  final TextEditingController password_controller = TextEditingController();
  final TextEditingController confirm_password_controller =
      TextEditingController();

  // 图片选择器
  final ImagePicker _picker = ImagePicker();

  // 头像上传中状态
  final RxBool is_avatar_uploading = false.obs;

  // 焦点控制器
  final FocusNode new_password_focus = FocusNode();

  // 表单key
  final form_key = GlobalKey<FormState>();

  // 是否显示密码
  final RxBool is_show_old_password = false.obs;
  final RxBool is_show_password = false.obs;
  final RxBool is_show_confirm_password = false.obs;

  // 表单类型（修改名称或密码）
  final Rx<FormType> form_type = FormType.name.obs;

  // 密码验证状态
  final RxBool old_password_verified = false.obs;

  _init_data() {
    try {
      final user_service = Get.find<UserService>();
      debugPrint("设置界面---当前用户：${user_service.user.value?.name}");
      // 如果用户数据为空，尝试重新获取
      if (user_service.user.value == null) {
        debugPrint("设置界面---当前用户为空，尝试重新获取");
        UserModel? current_user = user_service.get_now_user();
        if (current_user == null) {
          debugPrint("设置界面---无法获取当前用户数据，请检查登录状态");
          // 可以添加错误处理逻辑，例如显示错误提示或重定向到登录页面
          return;
        }
      }
      // 初始化表单控制器
      if (user_service.user.value != null) {
        name_controller.text = user_service.user.value!.name ?? '';
      }
    } catch (e) {
      debugPrint("设置界面初始化出错：$e");
    }
    update(["setting"]);
  }

  void onTap() {}

  void logout() {
    final user_service = Get.find<UserService>();
    user_service.logout_user();
    // 清除本地登录状态
    Storage().set_bool(Constants.login_status, false);
    Storage().set_string(Constants.current_user, "");

    // 跳转到主页
    RouteUtil.go(RouteNames.main);
    Get.find<MainController>().current_index = 0;
    Get.find<MainController>().update(["main"]);
  }

  void delete_user() {
    final user_service = Get.find<UserService>();
    SmartDialog.show(
      builder: (_) => AlertDialog(
        title: Text(
          'Delete Account',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
        content: Text(
          'Are you sure you want to delete your account?',
          style: TextStyle(
            color: Colors.white,
            fontSize: 14.sp,
            fontWeight: FontWeight.w400,
          ),
        ),
        backgroundColor: Color(0xff1E1E1E),
        actions: [
          TextButton(
            onPressed: () {
              SmartDialog.dismiss();
            },
            child: Text(
              'Cancel',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
          TextButton(
            onPressed: () {
              user_service.delete_user(user_service.user.value!.name!);
              logout();
            },
            child: Text(
              'Delete',
              style: TextStyle(
                color: Colors.red,
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      alignment: Alignment.bottomCenter,
    );
  }

  // 修改名称或密码
  void change_name_or_password() {
    final user_service = Get.find<UserService>();
    form_type.value = FormType.name; // 默认显示修改名称
    name_controller.text = user_service.user.value?.name ?? '';
    old_password_controller.clear();
    password_controller.clear();
    confirm_password_controller.clear();
    old_password_verified.value = false;
    SmartDialog.show(
      builder: (_) => const ChangeNamePasswordDialog(),
      onMask: null, // 防止点击遮罩关闭
      alignment: Alignment.bottomCenter,
    );
  }

  // 切换表单类型
  void toggle_form_type() {
    form_type.value = form_type.value == FormType.name
        ? FormType.password
        : FormType.name;
    // 清空密码字段
    old_password_controller.clear();
    password_controller.clear();
    confirm_password_controller.clear();
    old_password_verified.value = false;
  }

  // 切换旧密码可见性
  void toggle_old_password_visibility() {
    is_show_old_password.value = !is_show_old_password.value;
  }

  // 切换密码可见性
  void toggle_password_visibility() {
    is_show_password.value = !is_show_password.value;
  }

  // 切换确认密码可见性
  void toggle_confirm_password_visibility() {
    is_show_confirm_password.value = !is_show_confirm_password.value;
  }

  // 验证旧密码
  void verify_old_password() {
    final user_service = Get.find<UserService>();
    final current_user = user_service.user.value;
    if (current_user == null) {
      SmartDialogHelper.show_error('user not found');
      return;
    }

    final old_password = old_password_controller.text.trim();
    if (old_password.isEmpty) {
      SmartDialogHelper.show_warning('please enter the current password');
      return;
    }

    if (old_password != current_user.password) {
      SmartDialogHelper.show_error('current password is incorrect');
      return;
    }

    old_password_verified.value = true;

    // 验证成功后，聚焦到新密码输入框
    Future.delayed(Duration(milliseconds: 100), () {
      new_password_focus.requestFocus();
    });
  }

  // 保存修改
  void save_changes() {
    if (!form_key.currentState!.validate()) return;

    final user_service = Get.find<UserService>();
    final current_user = user_service.user.value;
    if (current_user == null) {
      debugPrint('当前用户为空');
      SmartDialog.dismiss();
      return;
    }

    if (form_type.value == FormType.name) {
      // 修改用户名
      final new_name = name_controller.text.trim();
      if (new_name == current_user.name) {
        debugPrint('用户名未更改');
        SmartDialog.dismiss();
        return;
      }

      // 检查用户名长度
      if (new_name.length > 12) {
        SmartDialogHelper.show_warning(
          'username cannot be more than 12 characters',
        );
        return;
      }

      // 检查用户名是否存在
      final usernameList = Storage().get_list(Constants.username_list);
      if (usernameList.contains(new_name) && new_name != current_user.name) {
        SmartDialogHelper.show_error('username already exists');
        return;
      }

      // 删除旧用户
      user_service.delete_user(current_user.name!);

      // 创建新用户
      final newUser = UserModel(
        id: current_user.id,
        name: new_name,
        password: current_user.password,
        avatar_image: current_user.avatar_image,
        plant_list: current_user.plant_list,
        water_lists: current_user.water_lists,
        is_vip: current_user.is_vip,
        like_lists: current_user.like_lists,
        signature: current_user.signature,
        post_lists: current_user.post_lists,
        comment_lists: current_user.comment_lists,
      );

      // 保存新用户
      user_service.register_user(newUser).then((success) {
        if (success) {
          user_service.set_user(newUser);
          debugPrint('用户名修改成功：$new_name');

          // 刷新社区页面，确保用户名更新
          if (Get.isRegistered<CommunityController>()) {
            Get.find<CommunityController>().refresh_posts();
          }

          // 刷新Mine页面
          if (Get.isRegistered<MineController>()) {
            Get.find<MineController>().load_user_data();
          }

          SmartDialog.dismiss();
          SmartDialogHelper.show_success('username modified successfully');
          update(["setting"]);
        } else {
          debugPrint('username modification failed');
          SmartDialogHelper.show_error('username modification failed');
        }
      });
    } else {
      // 修改密码
      // 先验证旧密码
      if (!old_password_verified.value) {
        verify_old_password();
        return;
      }

      final new_password = password_controller.text.trim();

      // 更新用户密码
      final updated_user = UserModel(
        id: current_user.id,
        name: current_user.name,
        password: new_password,
        avatar_image: current_user.avatar_image,
        plant_list: current_user.plant_list,
        water_lists: current_user.water_lists,
        is_vip: current_user.is_vip,
        like_lists: current_user.like_lists,
        signature: current_user.signature,
        post_lists: current_user.post_lists,
        comment_lists: current_user.comment_lists,
      );

      // 保存修改后的用户
      user_service.set_user(updated_user);
      debugPrint('密码修改成功');

      // 刷新Mine页面
      if (Get.isRegistered<MineController>()) {
        Get.find<MineController>().load_user_data();
      }

      SmartDialog.dismiss();
      SmartDialogHelper.show_success('password modified successfully');
    }
  }

  // 更新用户头像
  Future<void> update_avatar() async {
    final user_service = Get.find<UserService>();
    debugPrint('开始更新头像');
    try {
      // 显示加载状态
      is_avatar_uploading.value = true;
      update(["setting"]);

      // 从相册选择图片
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 600,
        maxHeight: 600,
        imageQuality: 85,
      );

      if (pickedFile == null) {
        debugPrint('未选择图片');
        is_avatar_uploading.value = false;
        update(["setting"]);
        return;
      }

      debugPrint('已选择图片: ${pickedFile.path}');

      // 保存图片到永久存储
      final String saved_image_path = await ImageStorageService().save_image(
        pickedFile,
      );

      debugPrint('保存的图片路径: $saved_image_path'); // 添加调试信息

      if (saved_image_path.isEmpty) {
        debugPrint('保存图片失败');
        is_avatar_uploading.value = false;
        SmartDialogHelper.show_error('failed to save image');
        update(["setting"]);
        return;
      }

      // 获取当前用户
      final current_user = user_service.user.value;
      if (current_user == null) {
        debugPrint('当前用户为空');
        is_avatar_uploading.value = false;
        update(["setting"]);
        return;
      }

      // 更新用户信息
      final updated_user = UserModel(
        id: current_user.id,
        name: current_user.name,
        password: current_user.password,
        avatar_image: saved_image_path, // 更新头像路径
        plant_list: current_user.plant_list,
        water_lists: current_user.water_lists,
        is_vip: current_user.is_vip,
        like_lists: current_user.like_lists,
        signature: current_user.signature,
        post_lists: current_user.post_lists,
        comment_lists: current_user.comment_lists,
      );

      // 保存更新后的用户
      user_service.set_user(updated_user);

      // 刷新社区页面
      Get.find<CommunityController>().refresh_posts();

      // 刷新Mine页面
      if (Get.isRegistered<MineController>()) {
        Get.find<MineController>().load_user_data();
      }

      debugPrint('头像更新成功: $saved_image_path');

      is_avatar_uploading.value = false;
      update(["setting"]);

      SmartDialogHelper.show_success('avatar updated successfully');
    } catch (e) {
      debugPrint('更新头像时发生错误: $e');
      is_avatar_uploading.value = false;
      update(["setting"]);
      SmartDialogHelper.show_error('failed to update avatar');
    }
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void onClose() {
    // 释放控制器资源
      name_controller.dispose();
    old_password_controller.dispose();
    password_controller.dispose();
    confirm_password_controller.dispose();
    new_password_focus.dispose();
    super.onClose();
  }
}

// 表单类型枚举
enum FormType { name, password }
